<?php

namespace app\admin\controller\user;


use app\admin\model\SystemErrorLog;
use app\admin\model\UserRecharge;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\db\Query;

/**
 * Class Recharge 会员充值
 * @package app\admin\controller\user
 * Author FashionJune
 * @ControllerAnnotation(title="充值管理")
 */
class Recharge extends AdminController
{

    protected $sort = [
        'id' => 'desc',
    ];

    protected $exWhere = ['user_id'];

    protected $allowModifyFields = ['remark'];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = UserRecharge::init();
//        $this->assign('auth_list', $this->model->getAuthList());
    }

    /**
     * @NodeAnotation(title="充值记录")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParams();
            $count = $this->model
                ->with(['user'])
                ->where($where)
                ->count();
            $list = $this->model
                ->with([
                    'user' => function (Query $query) {
                        $query->field(['id', 'nickname']);
                    },
                ])
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            //处理信息
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="充值")
     */
    public function inc()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'user_id' => 'require',
                'money' => 'require|float',
            ];
            $message = [
                'user_id.require' => '请填入会员id',
                'money.require' => '请填入充值金额',
                'money.float' => '充值金额必须为数字',
            ];
            $this->validate($post, $rule, $message);
            $re = $this->model->rechargeByAdmin($post);
            $re['status'] ? $this->success('充值成功') : $this->error($re['msg']);
        }
        return $this->fetch('', ['uid' => $this->request->get('id', '')]);
    }

    /**
     * @NodeAnotation(title="扣款")
     */
    public function dec()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'user_id' => 'require',
                'money_dec' => 'require|float',
            ];
            $message = [
                'user_id.require' => '请填入会员id',
                'money_dec.require' => '请填入扣款金额',
                'money_dec.float' => '扣款金额必须为数字',
            ];
            $this->validate($post, $rule, $message);
            $re = $this->model->decByAdmin($post);
            $re['status'] ? $this->success('扣款成功') : $this->error($re['msg']);
        }
        return $this->fetch('', ['uid' => $this->request->get('id', '')]);
    }


    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->except(['__token__', 'file']);
            $rule = [
            ];
            $message = [
            ];
            $this->validate($post, $rule, $message);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                SystemErrorLog::init()->addError($e->getMessage());
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
//        $row->auth_ids = explode(',', $row->auth_ids);
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
//        dd(config('app.user.delete'));
        //TODO 订单禁止删除
        !config('app.recharge.delete') && $this->error('请勿删除订单');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID' => 'require',
            'field|字段' => 'require',
            'value|值' => 'require',
        ];
        $this->validate($post, $rule);
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
        $row = $this->model->find($post['id']);
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }


}
